package com.pro.addresslist.tools;

import java.util.List;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
/** 
 * @author likehao
 * @Title: isPackageExists 
 */ 
public class SysUtil {
	
    /** 
     * @Title: isPackageExists 
     * @Description:  
     *      判断应用是否安装，传递的是应用的包名 
     *  
     * @param targetPackage 
     * @return       
     * @throws 
     */  
    public static boolean isPackageExists(String targetPackage,Context ct) {  
        List<ApplicationInfo> packages;  
        PackageManager pm;  
        pm = ct.getPackageManager();  
        packages = pm.getInstalledApplications(0);  
        for (ApplicationInfo packageInfo : packages) {  
            Log.i("application", "####package name : " + packageInfo.packageName);   
            if (packageInfo.packageName.equals(targetPackage)) {  
                return true;  
            }  
        }  
        return false;  
    }  
    /*
    * check the app is installed
    */
    public static boolean isAppInstalled(Context context,String packagename)
    {
    PackageInfo packageInfo;        
    try {
                packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
             }catch (NameNotFoundException e) {
                packageInfo = null;
                e.printStackTrace();
             }
             if(packageInfo ==null){
                //System.out.println("没有安装");
                return false;
             }else{
                //System.out.println("已经安装");
                return true;
            }
    }
    /** 
     * 获取应用版本号 
     * @return 当前应用的版本号 
     */  
    public static int getVersion(Context ct) {  
        try {  
            PackageManager manager = ct.getPackageManager();  
            PackageInfo info = manager.getPackageInfo(ct.getPackageName(), 0);  
            int version = info.versionCode;  
            return version;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return -1;  
        }  
    } 
     
    /** 
     * 返回当前程序版本名 
     */  
    public static String getAppVersionName(Context context) {  
        String versionName = "";  
        try {  
            // ---get the package info---  
            PackageManager pm = context.getPackageManager();  
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);  
            versionName = pi.versionName;  
            if (versionName == null || versionName.length() <= 0) {  
                return "";  
            }  
        } catch (Exception e) {  
            Log.e("VersionInfo", "Exception", e);  
        }  
        return versionName;  
    }  
}
